<?php

namespace app\admin\controller;

use app\admin\validate\CompanyUserValidate;
use app\service\traits\Crud;
use app\admin\model\CompanyUser as CompanyUserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

class CompanyUser extends Base
{
    private CompanyUserModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new CompanyUserModel();
        $this->validateClass = CompanyUserValidate::class;
        $this->withSearch    = 'name';
    }

    /**
     * 筛选框
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function search(): Response
    {
        $param = Request::param();
        $sql = $this->model;
        $sql  = $sql->withSearch($this->withSearch, $param);
        $field = 'id';
        if(request()->param('field')) $field .= ','.request()->param('field');
        $list = $sql->field($field)->order($this->orderSort)->select()->each(function($item) {
            $item->company_name = $item->company()->value('name');
        });
        return $this->success('获取成功', compact('list'));
    }
}